package com.feng.controller;

import com.feng.Exception.SystemException;
import com.feng.domain.ResponseResult;
import com.feng.domain.entity.LoginUser;
import com.feng.domain.entity.User;
import com.feng.domain.enums.AppHttpCodeEnum;
import com.feng.domain.vo.AdminUserInfoVo;
import com.feng.domain.vo.MenuVo;
import com.feng.domain.vo.RoutersVo;
import com.feng.domain.vo.UserInfoVo;
import com.feng.service.LoginService;
import com.feng.service.MenuService;
import com.feng.service.RoleService;
import com.feng.util.BeanCopyUtils;
import com.feng.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
public class AdminLoginController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private RoleService roleService;
    @PostMapping("/user/login")
    public ResponseResult login(@RequestBody User user){
         if(!StringUtils.hasText(user.getUserName())){
             throw new SystemException(AppHttpCodeEnum.REQUIRE_USERNAME);
         }
         return loginService.login(user);
    }
    @GetMapping("/getInfo")
    public ResponseResult<AdminUserInfoVo> getInfo(){
       //获取当前登录的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();

        //根据用户id查询权限信息
       List<String> perms=menuService.selectPermsByUserId(SecurityUtils.getUserId());
        //根据用户id查询角色信息
       List<String> roles=roleService.selectRoleKeyByUserID(SecurityUtils.getUserId());
        //返回userInfoVo
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(SecurityUtils.getLoginUser().getUser(), UserInfoVo.class);
        //封装数据返回
        AdminUserInfoVo adminuservo=new AdminUserInfoVo();
        adminuservo.setPermissions(perms);
        adminuservo.setRoles(roles);
        adminuservo.setUser(userInfoVo);
        return ResponseResult.okResult(adminuservo);
    }
    @GetMapping("/getRouters")
    public ResponseResult<RoutersVo> getRouters(){
        //查询menus 结果是tree的形式
       List<MenuVo> list=menuService.getRouterMenuTreeByUserId(SecurityUtils.getUserId());
        //封装数据返回，return
        RoutersVo routersVo=new RoutersVo(list);
        return ResponseResult.okResult(routersVo);

    }
    @PostMapping("/user/logout")
    public ResponseResult logout(){
       return loginService.logout();
    }

}
